//---------------------------------------------------------------------------
#pragma hdrstop
#include "TMessageManager.h"

//---------------------------------------------------------------------------

#pragma package(smart_init)
TMessageManager::TMessageManager(Client *client)
{
	   if(NULL==client)return;
	   SessionBox.clear();
	   _client=client;
	   _client->disco()->addFeature( XMLNS_CHAT_STATES );
	   _client->registerMessageSessionHandler( this, 0 );
}
//---------------------------------------------------------------------------
TMessageManager::~TMessageManager()
{
	 SessionBox.clear();
	 SessionBox.~list();
}
//---------------------------------------------------------------------------
void TMessageManager::handleMessage( const Message& msg, MessageSession * session )
{
	 _messageEventFilter->raiseMessageEvent( MessageEventDisplayed );
	 if(FOnMessage)FOnMessage(msg,session);
}
//---------------------------------------------------------------------------
void TMessageManager::handleMessageEvent( const JID& from, MessageEventType event )
{
	 if(FOnMessageEvent)FOnMessageEvent(from,event);
}
//---------------------------------------------------------------------------
void TMessageManager::handleChatState( const JID& from, ChatStateType state )
{
    if(FOnChatState)FOnChatState(from,state);
}
//---------------------------------------------------------------------------
void TMessageManager::handleMessageSession( MessageSession *session )
{
	  if(Put(session)){
		  session->registerMessageHandler( this );
		  _messageEventFilter = new MessageEventFilter( session );
		  _messageEventFilter->registerMessageEventHandler( this );
		  _chatStateFilter = new ChatStateFilter( session );
		  _chatStateFilter->registerChatStateHandler( this );
	  }
	if(FOnMessageSession)FOnMessageSession(session);
}
//---------------------------------------------------------------------------
bool __fastcall TMessageManager::Find(MessageSession *session,unsigned int *index,TSessionBox::iterator it)
{
	it=SessionBox.begin();
	unsigned int _index=0;
	for(;it!=SessionBox.end();it++,_index++)
	{
		 index=&_index;
		 if((*it)==session)return true;
	}
	return false;
}
//---------------------------------------------------------------------------
bool __fastcall TMessageManager::Put(MessageSession *session)
{
	 unsigned int index=0;
	 TSessionBox::iterator it;
	 if(Find(session,&index,it)){
		return false;
	 }else{
		SessionBox.push_front(session);
		return true;
	 }
}
//---------------------------------------------------------------------------
MessageSession * __fastcall TMessageManager::Find(unsigned int index,TSessionBox::iterator it)
{
	if(index<0||index>=SessionBox.size())return NULL;
	it=SessionBox.begin();
	return (*it);
}
